package com.soso.base.google.cron;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.soso.base.google.cron.schedule.ScheduleBean;
import com.soso.base.google.cron.schedule.ScheduleRuleChain;
import com.soso.base.google.cron.schedule.ScheduleRuleExecute;
import com.soso.base.util.log.Logger;
import com.soso.base.util.other.DateTools;

public abstract class AbstractBaseCron implements BaseCron{
	
	protected Map<String, Class<?>> subscribers = new HashMap<String, Class<?>>();
	private List<?> scheduleList=new ArrayList<Object>();
	public AbstractBaseCron(){
		registerSubscribers();
	}
	public List<?> getScheduleList() {
		return scheduleList;
	}
	public void setScheduleList(List<?> scheduleList) {
		this.scheduleList = scheduleList;
	}
	@Override
	public void subscribe(Enum<?> topic, Class<?> subscriber){
		subscribe(topic.name(), subscriber);
	}
	@Override
	public void subscribe(String topic, Class<?> subscriber) {
		subscribers.put(topic, subscriber);
	}
	@SuppressWarnings("unchecked")
	@Override
	public void execute() {
		Date nowDate=new Date();
		long time =nowDate.getTime();
		Logger.debug("当前时间："+DateTools.dateToStringWithFormat(nowDate, "yyyy/MM/dd HH:mm:ss"));
		for(ScheduleBean scheduleBean:(List<ScheduleBean>)scheduleList){
			Logger.debug("************************************************************************************");
			Logger.debug("计划任务："+scheduleBean.getTaskName()+":"+scheduleBean.getScheduleTime());
			if(scheduleBean.getLastTime()==null){
				scheduleBean.setLastTime(nowDate);
			}
			Logger.debug("上次执行时间："+DateTools.dateToStringWithFormat(scheduleBean.getLastTime(), "yyyy/MM/dd HH:mm:ss"));
			ScheduleRuleChain chain=new ScheduleRuleExecute();
			boolean isStart=chain.execute(scheduleBean);
			Logger.debug("isStart:"+isStart+",TaskName:"+scheduleBean.getTaskName()+",subscribers.containsKey:"+subscribers.containsKey(scheduleBean.getTaskName()));
			if(!isStart || scheduleBean.getTaskName()==null||!subscribers.containsKey(scheduleBean.getTaskName())) {
				Logger.debug("Invalid Schedule.");
				continue;
			}
			try {
				Subscriber subscriber=(Subscriber)subscribers.get(scheduleBean.getTaskName()).newInstance();
				subscriber.execute(scheduleBean);
			}catch (IllegalAccessException e) {
				Logger.error(e.getMessage());
			}catch (InstantiationException e) {
				Logger.error(e.getMessage());
			}
		}
		updateSchedules();
		time=System.currentTimeMillis()-time;
		Logger.info("执行时长："+time+"ms.");
	}
	protected abstract void registerSubscribers() ;
	protected abstract void updateSchedules() ;
}
